package com.vietnam.power.controller;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.vietnam.power.constant.AppConfigurationConstant;
import com.vietnam.power.domain.Article;
import com.vietnam.power.domain.ArticleSearchCriteria;
import com.vietnam.power.domain.MessageInfo;
import com.vietnam.power.domain.Product;
import com.vietnam.power.domain.ProductGroup;
import com.vietnam.power.domain.ProductSearchCriteria;
import com.vietnam.power.service.AppConfigurationService;
import com.vietnam.power.service.ArticleService;
import com.vietnam.power.service.ProductService;

@Controller
public class HomeController {
	private static Logger logger = Logger.getLogger(HomeController.class);

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private ProductService productService;

	@Autowired
	private ArticleService articleService;

	@Autowired
	private AppConfigurationService appConfigurationService;

	@RequestMapping(value = { "/", "/goHomePage" }, method = RequestMethod.GET)
	public ModelAndView goHomePage(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("go to homepage");
		ModelAndView mav = new ModelAndView("client/homepage");

		HashMap<Integer, List<Product>> productList = new HashMap<Integer, List<Product>>();
		List<ProductGroup> pgs = productService.getProductGroupAsClientMenu();
		for (ProductGroup pg : pgs) {
			ProductSearchCriteria psc = new ProductSearchCriteria();
			psc.setProductGroupId(pg.getId());
			psc.setMax(appConfigurationService.getAppConfigurationByName(AppConfigurationConstant.APP_CONFIGURATION.MAX_RECORDS_PER_MODULE)
					.getThreshold());
			List<Product> products = productService.searchProductByCriteria(psc, null);
			productList.put(pg.getId(), products);
		}
		mav.addObject("productListMap",productList);
		mav.addObject("pageTitle", messageSource.getMessage("top.header.homepage", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/goAboutUs" }, method = RequestMethod.GET)
	public ModelAndView goAboutUs(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("client/aboutUs");
		ArticleSearchCriteria asc = new ArticleSearchCriteria();
		asc.setArticleGroupName(AppConfigurationConstant.ARTICLE_GROUP.ABOUT_US);
		List<Article> artList = articleService.getArticleListByGroupName(asc, null);
		if (CollectionUtils.isNotEmpty(artList)) {
			mav.addObject("aboutUs", artList.get(0));
		}

		mav.addObject("pageTitle", messageSource.getMessage("top.header.about.us", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/goProducts" }, method = RequestMethod.GET)
	public ModelAndView goProducts(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("client/products");
		mav.addObject("productList", productService.searchProductByCriteria(null, null));
		mav.addObject("pageTitle", messageSource.getMessage("top.header.product", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/goNews" }, method = RequestMethod.GET)
	public ModelAndView goNews(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("client/news");
		ArticleSearchCriteria asc = new ArticleSearchCriteria();
		asc.setArticleGroupName(AppConfigurationConstant.ARTICLE_GROUP.NEWS);
		List<Article> artList = articleService.getArticleListByGroupName(asc, null);

		mav.addObject("newsList", artList);
		mav.addObject("pageTitle", messageSource.getMessage("top.header.news", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/goContact" }, method = RequestMethod.GET)
	public ModelAndView goContact(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="message",required=false) String message) {
		ModelAndView mav = new ModelAndView("client/contact");
		ArticleSearchCriteria asc = new ArticleSearchCriteria();
		asc.setArticleGroupName(AppConfigurationConstant.ARTICLE_GROUP.CONTACT);
		List<Article> artList = articleService.getArticleListByGroupName(asc, null);

		MessageInfo mi = new MessageInfo();
		if (CollectionUtils.isNotEmpty(artList)) {
			mav.addObject("contact", artList.get(0));
			mi.setTo(artList.get(0).getEmail());
		}
		mav.addObject("messageInfo", mi);
		
		if (StringUtils.equals(message, "success")) {
			mav.addObject("message", messageSource.getMessage("contact.send.success", null, LocaleContextHolder.getLocale()));
		}
		mav.addObject("pageTitle", messageSource.getMessage("top.header.contact", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping("/errorPage")
	public ModelAndView handleErrorPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("errorPage/errorPage");

		// Analyze the servlet exception
		Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		// String servletName = (String)
		// request.getAttribute("javax.servlet.error.servlet_name");
		String request_uri = (String) request.getAttribute("javax.servlet.error.request_uri");
		// String message = (String)
		// request.getAttribute("javax.servlet.error.message");

		if (request_uri == null) {
			request_uri = "Unknown";
		}

		String message = MessageFormat.format("Error code: {0}<br>Request URI: {1}<br>Message: {2}", statusCode, request_uri,
				getExceptionMessage(throwable, statusCode));

		mav.addObject("message", message);
		return mav;
	}

	private String getExceptionMessage(Throwable throwable, Integer statusCode) {
		if (throwable != null) {
			return throwable.getMessage();
		}
		HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
		return httpStatus.getReasonPhrase();
	}

}
